//
//  NYMemberCenterDataManager.m
//  NOAHWM
//
//  Created by Ryan on 13-5-14.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "NYMemberCenterDataManager.h"
#import "NSString+MD5.h"
#import "NSString+IPAddress.h"
#import "JSON.h"

@implementation NYMemberCenterDataManager

@synthesize loginMember;
@synthesize memberRoles;

#pragma mark - Public methods
- (BOOL)isLogin
{
    if(self.loginMember.accountId == nil || [self.loginMember.accountId isEqualToString:@""])
    {
        return NO;
    }
    else
    {
        return YES;
    }
}

- (void)logout
{
    //清空用户手势密码保存状态
    NSDictionary *userDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:kIsGestureAuthed];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:userDict];
    [dict setObject:@"0" forKey:[NYMemberCenterDataManager sharedManager].loginMember.accountId];
    [[NSUserDefaults standardUserDefaults] setObject:dict forKey:kIsGestureAuthed];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    //用户accountId清空
    loginMember.accountId = nil;
}

- (void)saveLoginMemberData
{
    NSData *memberData = [NSKeyedArchiver archivedDataWithRootObject:self.loginMember];
    NSString *userDataFilePath = [DOCUMENTS_FOLDER stringByAppendingPathComponent:kUserDataFile];
    [memberData writeToFile:userDataFilePath atomically:NO];
    
    NSData *memberRoleData = [NSKeyedArchiver archivedDataWithRootObject:self.memberRoles];
    NSString *userRoleDataFilePath = [DOCUMENTS_FOLDER stringByAppendingPathComponent:kUserRoleDataFile];
    [memberRoleData writeToFile:userRoleDataFilePath atomically:NO];
}

#pragma mark - Singleton methods

- (id)init
{
    if(self = [super init])
    {
        NSString *userDataFilePath = [DOCUMENTS_FOLDER stringByAppendingPathComponent:kUserDataFile];
        self.loginMember = [NSKeyedUnarchiver unarchiveObjectWithFile:userDataFilePath];
        if(nil == loginMember)
            loginMember = [[NYMember alloc] init];
        
        NSString *userRoleDataFilePath = [DOCUMENTS_FOLDER stringByAppendingPathComponent:kUserRoleDataFile];
        self.memberRoles = [NSKeyedUnarchiver unarchiveObjectWithFile:userRoleDataFilePath];
        if(nil == self.memberRoles)
            self.memberRoles = [NSMutableArray array];
    }
    return self;
}

+ (NYMemberCenterDataManager *)sharedManager
{
    static NYMemberCenterDataManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[NYMemberCenterDataManager alloc] init];
    });
    return manager;
}

- (void)dealloc
{
    [memberRoles release];
    [loginMember release];
    [super dealloc];
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    //jsonp({"message":"密码已发送到您的手机上，如有疑问请拨打客服热线400-820-0025咨询","result":"1","verifycode":"227336"})
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    if([downloader.purpose isEqualToString:kDynamicPasswordDownloaderKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            self.loginMember.dynPwd = [dict objectForKey:@"verifycode"];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDynamicPasswordResponseSucceedNotification object:[dict objectForKey:@"message"]];
        }
        else
        {
            self.loginMember.dynPwd = nil;
            [[NSNotificationCenter defaultCenter] postNotificationName:kDynamicPasswordResponseErrorNotification object:[dict objectForKey:@"message"]];
        }
    }
    else if([downloader.purpose isEqualToString:kResendDynamicPasswordDownloaderKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            self.loginMember.dynPwd = [dict objectForKey:@"verifycode"];
        }
        else
        {
            self.loginMember.dynPwd = nil;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:kResendDynPwdResponseNotification object:[dict objectForKey:@"message"]];
    }
    else if([downloader.purpose isEqualToString:kRegisterDownloaderKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"message"] rangeOfString:@"注册成功"].length > 0)
        {
            //注册成功，调用登录接口，获取会员相关信息
            NSString *md5UserName = loginMember.phoneNum;//[NSString md5HexDigest:loginMember.phoneNum];
            NSString *md5Password = [NSString md5HexDigest:loginMember.dynPwd];
            NSString *ipAddress = [NSString getIPAddress];
            
            NSString *subLoginUrl = [NSString stringWithFormat:kLoginUrl,@"jsonp",md5UserName,md5Password,ipAddress];
            subLoginUrl = [subLoginUrl stringByAppendingString:@"app000001"];
            NSString *loginUrl = [NSString stringWithFormat:@"%@%@",kServerAddress,subLoginUrl];
            loginUrl = [loginUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [[RYHUDManager sharedManager] startedNetWorkActivityWithText:@"注册成功，正在登录..."];
            [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:loginUrl delegate:self purpose:kLoginDownloaderKey];
        }
        else
        {
            [[RYHUDManager sharedManager]showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
        }
    }
    else if([downloader.purpose isEqualToString:kLoginDownloaderKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            NSArray *list = [dict objectForKey:@"list"];
            NSDictionary *dictUser = [list objectAtIndex:0];
            self.loginMember.accountId = [dictUser objectForKey:@"ACCOUNT_ID"];
            self.loginMember.accountName = [dictUser objectForKey:@"ACCOUNT_NAME"];
            self.loginMember.memberCardType = [dictUser objectForKey:@"MEMBER_CARD_TYPE"];
            self.loginMember.recordTypeName = [dictUser objectForKey:@"RECORD_TYPE_NAME"];
            self.loginMember.status = [dictUser objectForKey:@"STATUS"];
            self.loginMember.loginLogId = [dictUser objectForKey:@"login_log_id"];
            self.loginMember.is_gesture_password = [dictUser objectForKey:@"IS_GESTURE_PASSWORD"];
            self.loginMember.is_auth = [dictUser objectForKey:@"IS_AUTH"];
            [[RYHUDManager sharedManager] showWithMessage:@"注册成功" customView:nil hideDelay:2.f];
            [[NSNotificationCenter defaultCenter] postNotificationName:kUserChangeNotification object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshPersonalInfoNotification object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshApplyAuthNotificaiton object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kGetRegisterUserDataSuccessNotification object:nil];
        }
        else
        {
            [[RYHUDManager sharedManager]showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
        }
    }
    else if([downloader.purpose isEqualToString:kSendAdviceFeedbackKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
        }
        else{
            [[RYHUDManager sharedManager]showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
        }
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    if([downloader.purpose isEqualToString:kDynamicPasswordDownloaderKey])
    {
        self.loginMember.dynPwd = nil;
        [[NSNotificationCenter defaultCenter] postNotificationName:kDynamicPasswordResponseErrorNotification object:kNetWorkErrorString];
    }
    else if([downloader.purpose isEqualToString:kResendDynamicPasswordDownloaderKey])
    {
        self.loginMember.dynPwd = nil;
        [[NSNotificationCenter defaultCenter] postNotificationName:kResendDynPwdResponseNotification object:kNetWorkErrorString];
    }
    else if([downloader.purpose isEqualToString:kRegisterDownloaderKey])
    {
        [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
    }
    else if([downloader.purpose isEqualToString:kLoginDownloaderKey])
    {
        [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
    }
    else if([downloader.purpose isEqualToString:kSendAdviceFeedbackKey])
    {   
        [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
    }
}
@end
